﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Schema;

namespace General
{
    public class XSDValidator
    {
        private string _rutaxsd;
        private string _rutaxml;
        private string _fallo;

        public string RutaXSD
        {
            get { return this._rutaxsd; }
            set { this._rutaxsd = value; }
        }

        public string RutaXML
        {
            get { return this._rutaxml; }
            set { this._rutaxml = value; }
        }

        public string Fallo
        {
            get { return this._fallo; }
        }

        public XSDValidator()
        {
            _rutaxml = "";
            _rutaxsd = "";
        }

        public XSDValidator(string rutaXSD, string rutaXML)
        {
            this._rutaxsd = rutaXSD;
            this._rutaxml = rutaXML;
        }

        public bool validar()
        {
            System.IO.StreamReader fichxml = new System.IO.StreamReader(this.RutaXML);
            string pavalidar = fichxml.ReadToEnd();
            fichxml.Close();
            bool retorno;
            XmlReaderSettings opciones = new XmlReaderSettings();
            XmlReader lector = XmlReader.Create(new System.IO.StringReader(pavalidar), opciones);
            try
            {
                XmlSchemaSet esq = new XmlSchemaSet();
                esq.Add(String.Empty, XmlReader.Create(new System.IO.StreamReader(this.RutaXSD)));
                opciones.Schemas = esq;
                opciones.ValidationType = ValidationType.Schema;
                while (lector.Read()) { }

                retorno = true;
            }
            catch (XmlSchemaException xsdex)
            {
                _fallo = xsdex.Message;
                retorno = false;
            }
            catch (Exception ex)
            {
                _fallo = ex.Message;
                retorno = false;
            }
            finally
            {
                lector.Close();
            }
            return retorno;
        }
    }
}
